import path from 'path';
import fs from 'fs';
import * as vscode from 'vscode';
import { ExtensionService } from '../services/ExtensionService';


interface QueryOption{
    keywords: string;
    pageIndex: number ;
    pageSize: number;
}

interface FocusOption {
    time: number;
    title: string;
    groupId: string;
    content: string;
}

export class DocumentViewer{

    //#region 属性、方法
    private _panel!: vscode.WebviewPanel;
    private _disposables: vscode.Disposable[] = [];
    private _webviewReady = false;
    //#endregion

    constructor() {
        console.log('DocumentViewer.constructor');
        this.setupUI();

    }


    public OnReady: (() => void) | undefined;

    public OnDataRequest: ((option: QueryOption) => void) | undefined;

    public OnFoucusRequest: ((option: FocusOption) => void) | undefined;

    public OnGotoRequest: ((keywords: string) => void) | undefined;

    public OnHelpRequest: (() => void) | undefined;

    public OnOpenLinkRequest: ((link: string, docPath: string) => void) | undefined;

    public OnShowMessageRequest: ((text: string, level: string) => void) | undefined;

    public OnDispose: (() => void) | undefined;

    public pushData(data: any) {
        console.log('DocumentViewer.pushData');

        this._panel.webview.postMessage({
            cmd: 'loaded',
            data
        });
    }

    private static _columnCache: vscode.ViewColumn | undefined = undefined;

    private setupUI() {
        console.log('DocumentViewer.setupUI');
        
        if (DocumentViewer._columnCache === undefined) {
            DocumentViewer._columnCache = vscode.window.activeTextEditor
            ? vscode.ViewColumn.Beside
            : vscode.ViewColumn.One;
        }


        const localResourceRoots = [vscode.Uri.file(path.join(ExtensionService.ExtensionPath, 'dist', 'assets'))];

        this._panel = vscode.window.createWebviewPanel(
            'slPreview',
            `Sl预览器`,
            DocumentViewer._columnCache,
            {
                enableScripts: true,
                retainContextWhenHidden: true,
                localResourceRoots
            }
        );


        // 监听面板关闭
        this._panel.onDidDispose(() => this.dispose(), null, this._disposables);

        // 处理来自webview的消息
        this._panel.webview.onDidReceiveMessage(this.handleMessageFromWebview, this, this._disposables);


        
        this.initWebviewContent();
    }


    public setTitle(title: string) {
        setTimeout(() => {
            this._panel.title = title;
        }, 500);
    }

    public show() {
    }


    private initWebviewContent() {

        // 获取前端目录绝对路径
        const assetsPath = path.join(ExtensionService.ExtensionPath, 'dist', 'assets');
        const basePath = vscode.Uri.file(assetsPath);


        // 读取HTML模板
        const htmlPath = path.join(assetsPath, 'index.html');
        let html = fs.readFileSync(htmlPath, 'utf8');


        // 替换资源引用路径
        html = html.replace(
            /(<link.*?href="|<script.*?src="|<img.*?src=")(.*?)"/g,
            (match, prefix, src) => {
                const resourceUri = vscode.Uri.file(path.join(basePath.fsPath, src));
                return `${prefix}${this._panel.webview.asWebviewUri(resourceUri)}"`;
            }
        );

        // 注入 base 标签确保相对路径正确
        const baseHref = this._panel.webview.asWebviewUri(basePath) + '/';
        html = html.replace('<head>', `<head><base href="${baseHref}">`);

        html = html.replace('%_extensionVersion%', ExtensionService.ExtensionVersion);

        this._panel.webview.html = html;
    }





    private dispose() {
        this._panel.dispose();

        while (this._disposables.length) {
            const disposable = this._disposables.pop();
            if (disposable) {
                disposable.dispose();
            }
        }

        this.OnDispose?.();
    }


    private handleMessageFromWebview(message: any) {
        const { cmd } = message;
        if (!message.cmd) {
            return;
        }

        console.log('StorylineViewer:handleMessageFromWebview', cmd);

        switch (cmd) {
            case 'ui-ready':
                this._webviewReady = true;
                this.OnReady?.();
                break;
            case 'show-msg':
                const { text, level } = message;
                this.OnShowMessageRequest?.(text, level);
                break;
            case 'show-help':
                this.OnHelpRequest?.();
                break;
            case 'open-link':
                const {  link, docPath } = message;
                console.log('open-link:', link, docPath);
                this.OnOpenLinkRequest?.(link, docPath);
                break;
            case 'goTo':
                this.OnGotoRequest?.(message.keywords);
                break;
            case 'focus-event':
                const { time, title, groupId, content } = message;
                this.OnFoucusRequest?.({ 
                    time,
                    title,
                    groupId,
                    content
                 });
                break;
            case 'load-events':
                const { keywords, pageIndex, pageSize } = message;
                this.OnDataRequest?.({
                    keywords,
                    pageIndex,
                    pageSize});
                break;
            default:
                break;
        }
        

    }


}